'use strict';

window.APP={
    debug:true
};
//闭包限定命名空间
(function ($) {
    var index;
    var submitting;
    $.showLoading = function (timeout, msg) {
        if(timeout==undefined || timeout<1){
            timeout=10  ;
        }
        var tempIndex = index;
        index = layer.load(2, {time:timeout*1000}); //又换了种风格，并且设定最长等待10秒
        if (tempIndex != undefined) {
            layer.close(tempIndex);
        }
    };

    $.closeLoading = function () {
        if (index != undefined) {
            layer.close(index);
        }
    };

    $.showlog = function (msg, data) {
        if (window.APP != undefined && window.APP.debug === true) {
            if (data != undefined) {
                msg = $.extend({}, {msg: msg}, {data: data});
            }
            console.log(msg);
        }
    };

    $.showSuccessMsg=function(msg){
        if(msg==undefined ||msg==""){
            msg="操作成功"
        }
        layer.msg(msg, {icon: 1});
    }

    $.showErrorMsg=function(msg){
        if(msg==undefined ||msg==""){
            msg="操作失败"
        }
        layer.msg(msg, {icon: 2});
    }

    $.scopeGet = function (options) {
        var ajaxOptions = {
            type: 'GET'
        };
        ajaxOptions = $.extend({}, options, ajaxOptions);
        $.scopeAjax(ajaxOptions);
    };

    function isUndefined(value) {return typeof value === 'undefined';}


    function isNumber(value) {return typeof value === 'number';}


    function toJson(obj, pretty) {
        if (isUndefined(obj)) return undefined;
        if (!isNumber(pretty)) {
            pretty = pretty ? 2 : null;
        }
        return JSON.stringify(obj, undefined, pretty);
    }

    $.scopeAjax = function (options) {
        //提交中
        submitting = true;
        var defaults = {
            type: 'POST'
            //successMsg:null//'操作成功'
            //params:null,
            //appendParamsFunc:function () {}
            //successCallback: function (data) {/*不携带code，只处理成功内容*/},
        };
        if (options.type == undefined) {
            options.type = "POST";
        }
        var ajaxOptions = $.extend({}, defaults, options);
        if (ajaxOptions.type.toUpperCase() != 'GET') {
            if(options.appendParamsFunc == undefined){
                ajaxOptions.data =toJson(options.params)
            }else{
                ajaxOptions.data = toJson($.extend({}, options.params, options.appendParamsFunc()));
            }
            //$.showlog(ajaxOptions.data)
        }
        $.ajax(ajaxOptions).then(
            function (result) {
                if (result == undefined) {
                    //$.showErrMsg("返回空对象")
                    $.showlog("返回空对象", options);
                    return;
                }
                if (result.code == 1000) {
                    if (ajaxOptions.successCallback != undefined) {
                        ajaxOptions.successCallback(result.data);
                    }
                    else if (ajaxOptions.callback != undefined) {
                        ajaxOptions.callback(result.data);
                    } else {
                        $.showlog("未设置成功处理程序", result);
                    }
                    if (ajaxOptions.successMsg != undefined
                        && ajaxOptions.successMsg != "" && ajaxOptions.successMsg !== false) {
                        $.showSuccessMsg(ajaxOptions.successMsg);
                    }
                } else {
                    $.showlog(result);
                    $.showErrorMsg(result.msg);
                }
            })
            .fail(function (xhr) {
                $.showErrorMsg("系统异常，请稍后尝试");
            })
            .always(function (xhr) {
                submitting=false
            });
    };

    $.setupAjaxByOpts = function (opts) {
        var loginUrl;
        if (opts == undefined || opts.loginUrl == undefined) {
            loginUrl = "access.login";
        }
        else {
            loginUrl = opts.loginUrl;
        }
        var defaultOpts = {
            crsfcookiename: "x_csrftoken",
            dataType: 'json',
            crsfEnabled: false,
            contentType: 'application/json;charset=UTF-8',
            showErrorDirect: true,
            beforeSend: function (jqXHR, settings) {
                //改位置直接修改settings，可能不起作用，因为很多配置在 beforeSend之前已经作用在jqXHR上了
                $.appendCsrfTokenBeforeSend(jqXHR, settings);
                $.showLoading();
            },
            complete: function (xhr, status) {
                $.closeLoading();
            },
            dataFilter: function (result, a, b) {
                // $.showlog("ajax 结果", {result:result,a:a,b:b});
                try {
                    var apiresult = JSON.parse(result);
                    if (apiresult.code == 1002 || apiresult.code == 405) {
                        location.href=loginUrl;
                        return null;
                    } else if (apiresult.code != 1000) {
                        var msg = apiresult.msg;
                        if (msg == undefined || msg == "") msg = "未知错误";
                        $.showErrMsg(msg);
                    }
                    return result;
                } catch (e) {
                    $.showlog(e, result);
                    return result;
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                switch (jqXHR.status) {
                    case (404):
                        $.showErrMsg("未找到请求的资源");
                        break;
                    case (405):
                        $.showlog("暂不支持该方法", jqXHR);
                        location.href=loginUrl;
                        break;
                    case (401):
                        $.showlog("你没有访问权限", jqXHR);
                        $state.go(loginUrl);
                        break;
                    default:
                        $.showErrMsg("系统异常，请稍后尝试");
                        break
                }
                $.showlog("error", jqXHR);
            }
        };
        var setUpOptions = $.extend({}, defaultOpts, opts);
        return $.ajaxSetup(setUpOptions);
    };

    $.appendCsrfTokenBeforeSend = function (jqXHR, settings) {
        if (settings.crsfEnabled != true) return;
        if (settings.updateCookie === true) {
            //不需要crsftoken的访问
            //console.log("beforeSend:updateCookie" + settings.url);
            return;
        }
        //console.log("beforeSend:append csrf" + settings.url);
        var crsftoken = $.getAndcheckCrsfToken(settings);
        jqXHR.setRequestHeader('X-CSRF-TOKEN', crsftoken);
    };

    $.getAndcheckCrsfToken = function (opts) {
        var crsfcookiename = opts.crsfcookiename;
        if (crsfcookiename == undefined) {
            crsfcookiename = "x_csrftoken";
        }
        var crsftoken = $.cookie(crsfcookiename);
        if (crsftoken != undefined && crsftoken != "") {
            return crsftoken;
        }
        var url = opts.updateCookieUrl;
        if (url == undefined){
            url = "/gencookie";
        }
        $.ajax({
            url: url, updateCookie: true,
            async: false
        }).then(function (result) {
            //同步访问
        });
        return $.cookie(crsfcookiename);
    };

})(window.jQuery);

function formatDate(input) {
    if (input == undefined || input == '') return input;
    if (input == 'null') return '';
    var reg = /(\d{4}-\d{2}-\d{2}\d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2})/;
    if (reg.test(input)) {
        return input.substr(0, 10)
    }
    return input;
}

function formatDateAndAppendTime(input) {
    if (input == undefined || input == '') return input;
    if (input == 'null') return '';
    var reg = /(\d{4}-\d{2}-\d{2}\d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2})/;
    if (reg.test(input)) {
        return input.substr(0, 10) + " 00:00:00"
    }
    return input;
}

function formatTime(input) {
    if (input == undefined || input == '') return input;
    if (input == 'null') return '';
    var reg = /(\d{4}-\d{2}-\d{2}\d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2})/;
    if (reg.test(input) && input.length > 12) {
        return input.substr(11, input.length)
    }
    return "00:00:00";
}